package cn.starlightsoftware.sherly.exception;

import lombok.extern.slf4j.Slf4j;
import cn.starlightsoftware.sherly.exception.model.RpcExceptionModel;
import cn.starlightsoftware.sherly.model.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static cn.starlightsoftware.sherly.exception.enums.GlobalErrorCodeEnum.ACCESS_DENY;
import static cn.starlightsoftware.sherly.exception.enums.GlobalErrorCodeEnum.PARAMS_ERR;


@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @Value("${sherly.exception.message.enable:true}")
    private Boolean exceptionMessageEnable;

    @Value("${sherly.info.base-package}")
    private String basePackage;

    private final String DEFAULT_ERROR_MESSAGE = "系统异常，请联系服务商！";

    /**
     * 参数校验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class, ConstraintViolationException.class, BindException.class})
    public Result<?> validateExceptionHandler(Exception e) {
        e.printStackTrace();

        StringBuilder message = new StringBuilder();
        if (e instanceof MethodArgumentNotValidException) {
            // @RequestBody 方式校验
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
                message.append(fieldError.getField()).append(fieldError.getDefaultMessage()).append(";");
            }
        } else if (e instanceof ConstraintViolationException) {
            // @RequestParam 方式校验
            ConstraintViolationException ex = (ConstraintViolationException) e;
            message.append(ex.getMessage());
        } else {
            // get Model 方式校验
            BindException ex = (BindException) e;
            for (FieldError fieldError : ex.getFieldErrors()) {
                message.append(fieldError.getField()).append(fieldError.getDefaultMessage()).append(";");
            }
        }

        return Result.error(PARAMS_ERR, message.toString());
    }

    /**
     * 业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BizException.class)
    public Result<?> bizExceptionHandler(BizException e) {
        log.error("业务异常", e);
        return Result.error(e);
    }

    /**
     * 空指针异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    public Result<?> nullPointExceptionHandler(NullPointerException e) {
        log.error("空指针异常", e);
        return buildResult(e.toString(), e.getStackTrace());
    }

    /**
     * 其他异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result<?> exceptionHandler(Exception e) {
        log.error("其他未知异常", e);
        return buildResult(e.toString(), e.getStackTrace());
    }

    private Result<?> buildResult(String string, StackTraceElement[] stackTrace) {
        if (exceptionMessageEnable) {
            List<String> errorStack = Arrays.stream(stackTrace)
                    .map(StackTraceElement::toString)
                    .filter(msg -> msg.contains(basePackage))
                    .collect(Collectors.toList());
            return Result.error(new RpcExceptionModel(string, errorStack));
        }
        return Result.error(DEFAULT_ERROR_MESSAGE);
    }

    /**
     * security认证异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(AccessDeniedException.class)
    public Result<?> accessDeniedException(Exception e) {
        log.error("security认证异常", e);
        return Result.error(ACCESS_DENY);
    }
}
